# -*- coding:utf-8 -*-

import struct,codecs,re,Pluto,fnmatch

def makedic():
    dic={}
    tbl=codecs.open('in.tbl','r+b','utf_16')
    for line in tbl:
        line_split=line.replace('\r\n','').split(u'=')
        dic[line_split[1]]=line_split[0].lower()
    tbl.close()
    return dic

mydic=makedic()

def makestr(i):
    string=''
    j=0
    while j>=0:

        if u'★' in text[i+1+j]:
            break

        string+=text[i+1+j]
        j+=1
    return string[:-2]

def bytewrite(i,j):
    return chr(int(mydic[makestr(i)[j]],16))

def wordwrite(i,j):
    return chr(int(mydic[makestr(i)[j]][:2],16))+chr(int(mydic[makestr(i)[j]][2:4],16))

fl=Pluto.walk('script')
for fn in fl:
    if fnmatch.fnmatch(fn,'*.bin'):
        continue
    print fn
    target=open(fn[:-4]+'.bin','r+b')
    target.seek(4)
    start=struct.unpack('i',target.read(4))[0]
    end=struct.unpack('i',target.read(4))[0]
    target.seek(0x14)
    textoffset=struct.unpack('i',target.read(4))[0]
    textoffset2=(Pluto.size(fn[:-4]+'.bin')/16+1)*16
    pointer_list=[]
    for i in xrange(start,end,4):
        target.seek(i)
        if target.read(6)=='\x49\x00\x04\x00\x3B\x00':
            pointer_list.append(i+6)
    
    fp=codecs.open(fn,'rb','utf16')
    text=fp.readlines()
    line_num=len(text)
    
    offsetlist=[]
    target.seek(textoffset2)
    for i in xrange(line_num-1):
        if u'★' in text[i]:
            string=makestr(i)
            #print string
            if len(string)==0:
                continue
            offsetlist.append(target.tell()-textoffset)
            j=0
            while j<len(string):
    
                #如果读取的是回车符0d
                if ord(string[j])==13:
    
                    #写入换行符
                    target.write('\x40\x40')
                    j+=2
    
                #如果字符在字典里面，则导入
                if string[j] in mydic:
    
                    if len(mydic[string[j]])==4:
                        target.write(wordwrite(i,j))
    
                    if len(mydic[string[j]])==2:
                        target.write(bytewrite(i,j))
                    j+=1
            target.write('\x00')
    if len(pointer_list)!=len(offsetlist):
        print len(pointer_list)
        print len(offsetlist)
        print 'The num is not match!'
    
    num=len(pointer_list)
    for k in xrange(num):
        target.seek(pointer_list[k])
        target.write(struct.pack('H',offsetlist[k]))
    target.close()
    fp.close()
